package com.zidian.study.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.QuestionAdapter;
import com.zidian.study.bean.QuestioniareListBean;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/3 0003.
 * 问卷列表界面
 */
public class InteractionQuestionListActivity extends ToolBarActivity {

    @Bind(R.id.list)
    RecyclerView mRecyclerView;
    @Bind(R.id.swipe_refresh_widget)
    SwipeRefreshLayout mSwipeRefreshWidget;
    @Bind(R.id.no_data_view)
    LinearLayout noDataView;

    boolean isLoading;
    private QuestionAdapter adapter;
    private Handler handler = new Handler();
    private List<QuestioniareListBean.DateBean.QuestionnaireListBean> data = new ArrayList<>();
    private int startrow = 1;
    private boolean isRefreshing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_interaction_question_list);
        setTitle("问卷调查");
        ButterKnife.bind(this);
        initView();
        initData();
    }

    public void initView() {

        mSwipeRefreshWidget.setColorSchemeResources(R.color.green);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                isRefreshing = true;
                mSwipeRefreshWidget.setRefreshing(true);
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        isRefreshing = true;
                        try {
                            startrow = 1;
                            getData(startrow);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, 2000);

            }
        });
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        final LinearLayoutManager layoutManager = new LinearLayoutManager(InteractionQuestionListActivity.this);
        adapter = new QuestionAdapter(this, data);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");
                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        try {
                            getData(startrow + 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.d("test", "load more completed");
                        isLoading = false;

                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new QuestionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                Intent intent = new Intent();
                if (data.get(position).getQuestionnaireExplain().equals("就业质量")) {

                    intent.setClass(context, JobsQuestionActivity.class);
                    intent.putExtra("url", data.get(position).getQuestionnaireURL());

                } else {
                    intent.setClass(context, InteractionQstDetailActivity.class);
                    intent.putExtra("questionnaireId", data.get(position).getQuestionnaireId());
                }
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

    }

    public void initData() {
//        try {
//            run("0");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        try {
            getData(startrow);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void getData(int startrow) throws IOException {
        String url = Constant.URL_TEACHER + "Questionnaire/selectStuQues";

        Map<String, String> map = new HashMap<>();
        map.put("startrow", startrow + "");
        map.put("pageSize", "10");
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
            }

            @Override
            public void onResponse(String response, int id) {
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
                Log.e("T", response);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        if (resultCode == 201) {
                            isLoading = false;
                            adapter.setMore(false);
                            noDataView.setVisibility(View.VISIBLE);
                            return;
                        }

                        ToastUtil.showToast(InteractionQuestionListActivity.this, jsonObject.getString("message"));
                        return;
                    }

                } catch (JSONException e) {


                }

                Gson gson = new Gson();
                QuestioniareListBean model = gson.fromJson(response, QuestioniareListBean.class);
//
                if (model.isSuccess()) {
                    if (model.getData() == null) {
                        return;
                    }
                    if (model.getData().getQuestionnaireList().size() < 10) {
                        isLoading = true;
                        adapter.setMore(false);
                    } else {
                        isLoading = false;
                        adapter.setMore(true);
                    }
//                    dataBeanList.addAll(actionBean.getData());
//                    getData();
                    data.addAll(model.getData().getQuestionnaireList());
                    adapter.notifyDataSetChanged();
                    mSwipeRefreshWidget.setRefreshing(false);
                    adapter.notifyItemRemoved(adapter.getItemCount());
                    noDataView.setVisibility(View.GONE);
                }

            }
        });

    }
}
